package com.funsport.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.PageResult;
import com.funsport.common.Result;
import com.funsport.entity.Venue;
import com.funsport.security.DataPermissionHelper;
import com.funsport.security.SecurityUtils;
import com.funsport.service.IVenueService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Web管理端场地Controller
 *
 * @author Fun-Sport Team
 */
@Slf4j
@Tag(name = "Web管理端场地", description = "Web管理端场地管理接口")
@RestController
@RequestMapping("/web/venue")
@RequiredArgsConstructor
public class WebVenueController {

    private final IVenueService venueService;
    private final DataPermissionHelper dataPermissionHelper;

    @Operation(summary = "获取场地列表")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @GetMapping("/list")
    public Result<PageResult<Venue>> getVenueList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        // 数据权限过滤：场地管理员只能看到自己管理的场地
        LambdaQueryWrapper<Venue> queryWrapper = new LambdaQueryWrapper<>();
        
        if (dataPermissionHelper.isVenueManager() && !dataPermissionHelper.canViewAllData()) {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            queryWrapper.eq(Venue::getManagerId, currentUserId);
            log.info("场地管理员数据过滤: userId={}", currentUserId);
        }
        
        queryWrapper.orderByDesc(Venue::getCreatedAt);
        
        Page<Venue> pageParam = new Page<>(page, pageSize);
        Page<Venue> result = venueService.page(pageParam, queryWrapper);
        
        return Result.success(PageResult.build(
                result.getRecords(), result.getTotal(), page, pageSize));
    }

    @Operation(summary = "创建场地")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @PostMapping("/create")
    public Result<Long> createVenue(@Valid @RequestBody Venue venue) {
        Long managerId = SecurityUtils.getCurrentUserId();
        venueService.createVenue(venue, managerId);
        return Result.success("场地创建成功", venue.getId());
    }

    @Operation(summary = "获取场地详情")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @GetMapping("/{id}")
    public Result<Venue> getVenueDetail(@PathVariable Long id) {
        Venue venue = venueService.getById(id);
        return Result.success(venue);
    }

    @Operation(summary = "更新场地信息")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @PutMapping("/{id}")
    public Result<Void> updateVenue(@PathVariable Long id, @Valid @RequestBody Venue venue) {
        venue.setId(id);
        venueService.updateById(venue);
        return Result.success("场地更新成功", null);
    }

    @Operation(summary = "更新场地状态")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @PostMapping("/{id}/status")
    public Result<Void> updateVenueStatus(
            @PathVariable Long id,
            @RequestParam String status) {
        Long managerId = SecurityUtils.getCurrentUserId();
        venueService.updateVenueStatus(id, status, managerId);
        return Result.success("场地状态已更新", null);
    }

    @Operation(summary = "检查场地可用性")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @GetMapping("/{id}/availability")
    public Result<Boolean> checkAvailability(
            @PathVariable Long id,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        boolean available = venueService.isVenueAvailable(id, startTime, endTime);
        return Result.success(available);
    }

    @Operation(summary = "预订场地")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @PostMapping("/{id}/book")
    public Result<Void> bookVenue(
            @PathVariable Long id,
            @RequestParam Long eventId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        Long userId = SecurityUtils.getCurrentUserId();
        venueService.bookVenue(id, eventId, startTime, endTime, userId);
        return Result.success("场地预订成功", null);
    }

    @Operation(summary = "取消场地预订")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @PostMapping("/{id}/cancel-booking")
    public Result<Void> cancelBooking(
            @PathVariable Long id,
            @RequestParam Long eventId) {
        venueService.cancelVenueBooking(id, eventId);
        return Result.success("已取消场地预订", null);
    }

    @Operation(summary = "搜索场地")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @GetMapping("/search")
    public Result<List<Venue>> searchVenues(
            @RequestParam(required = false) String city,
            @RequestParam(required = false) Long sportTypeId) {
        List<Venue> venues = venueService.searchVenues(city, sportTypeId);
        return Result.success(venues);
    }

    @Operation(summary = "获取我管理的场地")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER')")
    @GetMapping("/my-venues")
    public Result<List<Venue>> getMyVenues() {
        Long managerId = SecurityUtils.getCurrentUserId();
        List<Venue> venues = venueService.getVenuesByManager(managerId);
        return Result.success(venues);
    }
}

